package xcmd

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 根据视频获取视频宽高，返回单位：px
//
//	filepath	视频地址
func Video2wh(filepath string) (uint, uint, error) {
	if err := CheckCommand("bash", "sed", "ffmpeg", "cut", "grep"); err != nil {
		return 0, 0, err
	}
	if filepath == "" {
		return 0, 0, errors.New("文件路径不能为空")
	}
	if _, err := os.Stat(filepath); err != nil {
		// 文件不存在
		return 0, 0, errors.New("文件不存在")
	}
	filepath = strings.ReplaceAll(filepath, " ", "\\ ")
	out, err := Exec(GetCommand("bash"), "-c", GetCommand("ffmpeg")+" -i "+filepath+" 2>&1 | "+
		GetCommand("grep")+" Stream | "+
		GetCommand("grep")+" Video | "+
		GetCommand("cut")+" -d ',' -f 4 | "+
		GetCommand("cut")+" -d ' ' -f 2 | "+
		GetCommand("sed")+" s/\\ //")
	if err != nil {
		return 0, 0, err
	}
	if out == "" {
		// 无输出信息
		return 0, 0, errors.New("输出信息为空")
	}
	wh := strings.Split(out, "x")
	if len(wh) != 2 {
		for _, v := range wh {
			fmt.Println(v)
		}
		return 0, 0, errors.New("视频宽高获取失败:" + out)
	}
	return xstring.ToUint(wh[0]), xstring.ToUint(wh[1]), nil
}
